<template>
    <!-- 活动管理-新闻模块页面 -->
    <div class="app-container">
    <!-- 搜索工具栏 -->
    <section>
      <so-tool-bar :toolData="toolData" :query="listQuery" @search="search" />
    </section>
     <!-- 其他操作 -->
    <section class="filter-container">
      <el-row>
        <el-col :span="15">
          <el-button class="filter-item" type="primary" size="small" @click="haveTop(1)">置顶</el-button>
          <el-button class="filter-item" type="primary" size="small" @click="haveTop(0)">取消置顶</el-button>
        </el-col>
        <el-col :span="9">
          <section style="float: right">
            <el-button class="filter-item" type="danger" size="small" @click="delRows">批量删除</el-button>
            <el-button class="filter-item" type="primary" size="small" @click="openForm('add')">发布帖子</el-button>
          </section>
        </el-col>
      </el-row>
    </section>
    <!-- 表格 -->
    <el-table :data="tableList" v-loading="loading" element-loading-text="正在查询中。。。" stripe highlight-current-row @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column align="center" width="30">
        <template slot-scope="scope">
          <i class="iconfont ali-zhiding" v-show="scope.row.top_status == 1"></i>
        </template>
      </el-table-column>
      <el-table-column align="center" label="新闻主题" prop="title">
      </el-table-column>
      <el-table-column align="center" label="发布人" prop="create_user">
      </el-table-column>
      <el-table-column align="center" label="发布时间" prop="create_time">
      </el-table-column>
      <el-table-column align="center" label="列表链接">
        <template slot-scope="scope">
          <el-button
            v-clipboard:copy="'https://cloud.anyolife.com/NewsHome'"
            v-clipboard:success="onCopy"
            v-clipboard:error="onError"
            type="text"
          >复制链接</el-button>
        </template>
      </el-table-column>
      <!-- <el-table-column align="center" label="详情链接">
        <template slot-scope="scope">
          <el-button
            v-clipboard:copy="'https://cloud.anyolife.com/ActivityDetail' + '?id=' + scope.row.id
            + '&status=' + scope.row.active_status + '&name=' + 'home'"
            v-clipboard:success="onCopy"
            v-clipboard:error="onError"
            type="text"
          >复制链接</el-button>
        </template>
      </el-table-column> -->
      <el-table-column align="center" label="操作" width="230px">
        <template slot-scope="scope">
          <el-button type="text" size="mini" @click="delRow(scope.row)">删除</el-button>
          <el-button type="text" size="mini" @click="editRow('edit',scope.row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <section>
      <so-pagination :query="listQuery" @initList="initList"/>
    </section>
     <!-- 发布新闻 -->
    <section>
      <el-dialog :visible.sync="dialog.isShow" :show-close="false" :fullscreen="fullscreen" :before-close="beforeClose" :close-on-click-modal="false">
        <el-row slot="title">
          <el-col :span="10" style="padding-top: 5px">
            <span style="font-size: 18px;">{{dialog.title}}</span>
          </el-col>
          <el-col :span="2" :offset="11">
            <el-button type="text" v-if="!fullscreen" icon="iconfont ali-quanping" @click="fullscreen = true" style="float: right"></el-button>
            <el-button type="text" v-else icon="iconfont ali-zuixiaohua" @click="fullscreen = false" style="float: right"></el-button>
          </el-col>
          <el-col :span="1">
            <el-button type="text" icon="iconfont ali-guanbi" @click="dialog.isShow = false" style="float: right"></el-button>
          </el-col>
        </el-row>
        <el-form :model="form" ref="createArticle" label-width="90px">
          <el-form-item label="新闻主题" prop="title" :rules="filter_rules({required:true})">
            <el-input clearable style="width: 300px;" placeholder="请输入主题" v-model.trim="form.title">
            </el-input>
          </el-form-item>
          <el-form-item label="活动封面" prop="banner_path" :rules="filter_rules({type: 'upload'})">
            <img v-if="form.banner_path" :src="form.banner_path" class="avatar" @click="sizeSet">
            <i v-else class="el-icon-plus avatar-uploader-icon" @click="sizeSet"></i>
          </el-form-item>
          <!-- <el-form-item label="内容类型" prop="content_type" :rules="filter_rules({required:true})">
            <el-select style="width: 300px;" v-model="form.content_type" clearable placeholder="请选择" @change="selectChange">
              <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item> -->
          <el-form-item v-if="selectId != 1" prop="study_content" label="学习内容" :rules="filter_rules({required:true})">
            <UE @showUpload="showUpload" :defaultMsg.sync='defaultMsg' ref="ue"></UE>
          </el-form-item>
          <el-form-item v-else label="链接" prop="link_url" :rules="filter_rules({required:true})">
            <el-input clearable style="width: 300px;" placeholder="请输入链接" v-model.trim="form.link_url">
            </el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialog.isShow = false">取 消</el-button>
          <el-button type="primary"  @click.native="validate('createArticle')">提 交</el-button>
        </span>
      </el-dialog>
    </section>
     <!-- 上传图片 组件 -->
    <section>
      <size-temp ref="size" :img.sync="form.banner_path" title="图片设置"></size-temp>
    </section>
    <section>
      <size-temp ref="vupload" @addUeditorImg="addUeditorImg" img="卐" title="添加图片"></size-temp>
    </section>
    </div>
</template>

<script>
import { searchTool} from '@/utils'
import SoPagination from '@/components/SoPagination'     //分页
import SoToolBar from '@/components/SoToolBar'          //搜索工具
import { status_opt, audit_status, toolData } from './community'
import sizeTemp from '@/components/draggableSize'      //上传图片控件
import {news_list, news_listAll, news_save, news_edit, news_delete, news_deleteAll, news_findById, updateTopStatus} from '@/api/newsModule'   //接口
import { create } from 'domain';
import UE from '@/components/Ueditor';

export default {
    name: "newsModule",
    components: { SoToolBar, SoPagination, sizeTemp, UE },
    data(){
        return{
          form: { banner_path: '' },
          fullscreen: false,
          dialog: { isShow: false },
          //表格数据
          tableList:[],
          loading: false,
          toolData: toolData, //搜索工具栏初始化
          multipleSelection: [],
          defaultMsg: '',
          selectId: '1', // 选中的值 
          listQuery: { start: 0, limit: 10, total: 0, current: 1, content_type: 1},
          options:[
            {
              id: 1,
              name: '链接'
            }, 
            {
              id: 0,
              name: '自定义'
            }
          ]
        }
    },
    methods:{
    onCopy: function() {
      this.$message({
        type: "success",
        message: "复制成功"
      });
    },
    onError: function() {
      this.$message.error("复制失败");
    },
    //置顶
    async haveTop(e) {//1 置顶 0 取消
      if (this.multipleSelection.length == 0) {
        this.$message.warning('请先选择需要调整单元');
        return;
      }
      const ids = this.multipleSelection.map(item => item.id).join();
      this.loading = true;
      let { data } = await updateTopStatus({ ids: ids, top_status: e });
      this.loading = false;
      if (data.status === 100) {
        await this.initList();
        this.$message.success('操作成功');
      }
    },
    addUeditorImg(val){
      this.$refs.ue.addToContent(`<img src="${val}">`)
    },
    sizeSet(){
      this.$refs.size.open()
    },
    beforeClose(done){
    // this.$refs.ue.clear();
      this.dialog.isShow=false;
    done()
    },
    async delRow(data) {  //删除
      let Id = data.id
      try {
        let res = await this.$confirm("确认删除吗？");
        if (res == "confirm") {
          this.loading = true;
          let { data } = await news_delete({ id: Id });
          if (data.status == 100) {
            this.$message.success("删除成功");
          }
          this.initList();
          this.loading = false;
        }
      } catch (error) {
        console.log(error, "error");
      }
    },
    showUpload(){
      this.$refs.vupload.open()
    },
    // 查询数据
    async initList(){
      this.loading = true;
      const query = {...this.listQuery, company_id:localStorage.getItem("companyId") - 0};
      let {data} = await news_list(query);
      this.loading = false;
      if(data.status === 100){
        this.tableList = data.data.rows;
        this.listQuery.total = data.data.results;
        this.inhand_count = data.data.inhand_count;
      }
    },
    selectChange(value){
      this.selectId = value
      if (value !== 1) {
        this.defaultMsg = ''//清空富文本
        this.$nextTick(_ => {
          this.$refs.ue.setContent('<br/>'); //清空富文本
        });
      } else {
        this.form.link_url = ""
      }
    },
    async openForm() {//打开发布新闻dialog
      this.fromStatus = 'add'
      this.defaultMsg = ''//清空富文本
      this.selectId = 1
      this.form = { banner_path: '' }
      this.dialog = { isShow: true, title: '发布新闻' }
      if (this.selectId != 1) {
        this.$nextTick(_ => {
            this.$refs.ue.setContent('<br/>'); //清空富文本
        });
      }
    },

    async editRow(e, row) {//编辑
      this.fromStatus = 'edit'
      this.selectId = row.content_type
      this.defaultMsg = row.study_content
      if (row.content_type !== 1) {
        this.$nextTick(_ => {
          this.$refs.ue.setContent(row.study_content);
        });
      }
      let { data } = await news_findById({ id: row.id });
      if (data.status === 100) {
        this.form = data.data
        this.dialog = { isShow: true, title: '编辑新闻' }
      }
    },
    // 搜索
    search() {
      let keyWords = { key: 'searchDate', names: ['news_start_time', 'news_end_time'] }
      this.listQuery = searchTool(this.listQuery, keyWords);
      this.initList();
    },
    //批量删除
    async delRows() {//批量删除
      if (this.multipleSelection.length == 0) {
        this.$message.warning("请先选择需要调整单元");
        return;
      }
      const ids = this.multipleSelection.map(item => item.id).join();
      try {
        const res = await this.$confirm("确认删除吗？");
        if (res == "confirm") {
          this.loading = true;
          const { data } = await news_deleteAll({ array: ids });
          if (data.status == 100) {
            this.$message.success("删除成功");
          }
          this.initList();
        }
      } catch (error) {
        console.log(error, "error");
      }
    },

    handleSelectionChange(e) {//
      this.multipleSelection = e;
    },
    async saveObj() {
      const params = { ...this.form, company_id: localStorage.getItem("companyId") - 0 };
      this.loading = true;
      let { data } = this.fromStatus == 'add' ? await news_save(params) : await news_edit(params);
      this.loading = false;
      if (data.status == 100) {
        this.$message.success(this.fromStatus == 'add' ? '提交成功' : '编辑成功')
        this.initList();
        }
    },
    // 保存
    validate(e) {

      this.form.study_content = ''
      this.form.content_type = 1
      this.$refs[e].validate(valid => {
        if (valid) {
          this.saveObj();
          this.dialog.isShow = false
        } else {
          return false;
        }
      })
    },

    },

    created(){
      this.initList();
    },

    handleAvatarSuccess(res, file) {
      this.form.banner_path = this.ossPublicUrl + "/" + res.data.banner_path;
    },
}
</script>
<style lang="scss" scoped>
$border: 1px dashed #d9d9d9;
$picture-size: 120px;
$color: #606266;
span {
  font-size: 13px;
  color: $color;
}
.ali-zhiding{
  color: #009900;
  font-size: 20px;
}
.avatar-uploader {
  .el-upload {
    border: $border;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    &:hover {
      border-color: #409eff;
    }
  }
}
.avatar-uploader-icon {
  border: $border;
  font-size: 28px;
  color: #8c939d;
  width: $picture-size;
  height: $picture-size;
  line-height: $picture-size;
  text-align: center;
  border-radius: 5px;
  cursor: pointer;
}
.avatar {
  width: 60%;
  display: block;
  border-radius: 5px;
  cursor: pointer;
}
</style>
